{% extends "base.html" %}

{% block title %}BunnyWrite - Practice Writing{% endblock %}

{% block styles %}
<link rel="stylesheet" href="{{ url_for('static', filename='write.css') }}">
{% endblock %}

{% block content %}
    <div class="writing-container">
        <h1 class="writing-title">Free Writing</h1>
        <div class="input-wrapper">
            <textarea id="writing-input" class="writing-area" placeholder="Start writing in English..."></textarea>
            <div id="loading-spinner" class="loading-spinner"></div>
        </div>
    </div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    let typingTimer;
    const doneTypingInterval = 2000; // 2 seconds

    const writingInput = document.getElementById('writing-input');
    const loadingSpinner = document.getElementById('loading-spinner');
    let currentCompletion = '';

    writingInput.addEventListener('input', function() {
        const words = this.value.trim().split(/\s+/);
        console.log('Word count:', words.length);
        if (words.length >= 5) {
            console.log('Setting timer for completion');
            clearTimeout(typingTimer);
            typingTimer = setTimeout(() => {
                loadingSpinner.style.display = 'block';
                getCompletion();
            }, doneTypingInterval);
        }
    });

    writingInput.addEventListener('keydown', function(e) {
        console.log('Key pressed:', e.key);
        if (e.key === 'Tab' && currentCompletion) {
            e.preventDefault();
            const selectionStart = writingInput.selectionStart;
            const selectionEnd = writingInput.selectionEnd;
            
            if (selectionStart !== selectionEnd) {
                document.execCommand('foreColor', false, '#000');
                writingInput.setSelectionRange(writingInput.value.length, writingInput.value.length);
            }
            currentCompletion = '';
        }
    });

    async function getCompletion() {
        const text = writingInput.value;
        console.log('Requesting completion for:', text);
        try {
            const response = await fetch('/api/get-completion', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ text: text })
            });
            const data = await response.json();
            console.log('Received completion:', data.completion);
            currentCompletion = ' ' + data.completion;
            
            const combinedText = text + currentCompletion;
            writingInput.value = combinedText;
            
            writingInput.setSelectionRange(text.length, combinedText.length);
            document.execCommand('foreColor', false, '#888');
            writingInput.focus();
            loadingSpinner.style.display = 'none';
        } catch (error) {
            console.error('Error getting completion:', error);
            loadingSpinner.style.display = 'none';
        }
    }
});
</script>
{% endblock %}
